#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int shared_data = 0;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

// 读线程函数
void* reader(void* arg) {
    int id = *(int*)arg;
    for (int i = 0; i < 5; i++) {
        pthread_rwlock_rdlock(&rwlock);  // 获取读锁
        printf("Reader %d: read value = %d\n", id, shared_data);
        pthread_rwlock_unlock(&rwlock);  // 释放锁
        usleep(100000);  // 模拟读取耗时
    }
    return NULL;
}

// 写线程函数
void* writer(void* arg) {
    int id = *(int*)arg;
    for (int i = 0; i < 3; i++) {
        pthread_rwlock_wrlock(&rwlock);  // 获取写锁（独占）
        shared_data++;
        printf("Writer %d: updated to %d\n", id, shared_data);
        pthread_rwlock_unlock(&rwlock);  // 释放锁
        usleep(200000);  // 模拟写入耗时
    }
    return NULL;
}

int main() {
    pthread_t readers[3], writers[2];
    int ids[] = {1,2,3,1,2};  // 线程ID

    // 创建3个读线程
    for (int i = 0; i < 3; i++) 
        pthread_create(&readers[i], NULL, reader, &ids[i]);
    
    // 创建2个写线程
    for (int i = 0; i < 2; i++) 
        pthread_create(&writers[i], NULL, writer, &ids[i+3]);
    
    // 等待所有线程结束
    for (int i = 0; i < 3; i++) pthread_join(readers[i], NULL);
    for (int i = 0; i < 2; i++) pthread_join(writers[i], NULL);
    
    pthread_rwlock_destroy(&rwlock);
    return 0;
}
